<?php
/** "Abstract" Delete action: can not be executed, only subclassed with override of verifyArguments()
 *
 *
 */
class Yz_Action_Delete
    extends Yz_Action_Abstract
{


    /************************************
     *        Protected methods         *
     ************************************/

    /** Verify arguments before building query
     *      prevent deletion without sensible arguments
     *  @return this
     */
    protected function verifyArguments()
    {
        debug();
        throw StateError::_new_();
        //throw error("Forbidden to Delete without argument verification");
    }

    /**
     *  Common Delete statement creator:
     *      the common part of statement
     *  @return Yz_SQL_Statement_Delete
     */
    protected function buildStatement()
    {
        debug();
        $this->inspectModel();
        return Yz_SQL_Statement_Delete::create()
            ->delete(array_keys($this->tables))
            ->from($this->tables)
        ;
    }


    /** Inspect a model and determine what (fields) and from where (tables) will be selected
     *  @param Yz_Model_Interface $model
     *  @param string $alias
     *  @return Yz_Array fields
     */
    protected function doInspectModel(Yz_Model_Interface $model, $alias)
    {
        debug();
        $origModel = $model;
        while ($parent = $model->getParentModel()) {
            // recursively add sources for parent models
            $this
                ->addParentSource($model, $parent)
            ;
            $model = $parent;
        }
        return $this;
    }

    /** Add the parent model's table to table list
     *  @param $origModel
     *  @param $parentModel
     */
    protected function addParentSource($origModel, $parentModel)
    {
        debug("Add Parent {$parentModel}");
        $parentAlias = $parentModel->getName();
        $this->tables[$parentAlias] = Yz_SQL_Join::innerJoin(
            $parentModel->getSourceName(),
            $parentAlias
        )->joinUsing('id');
        return $this;
    }

}
